import os
from django.shortcuts import render,HttpResponse,redirect
from django import forms
from app02 import models
from django.conf import settings
from app02.utils.bootrsap import BootrsapForm,BootrsapModelForm

def upload_list(request):
    if request.method == 'GET':
        return render(request,'upload_list.html')
    # print(request.POST)  #请求体中的数据
    # print(request.FILES)  #请求发过来的文件{}

    file_object=request.FILES.get('atter')
    #print(file_object.name)  文件名   xxx.png

    f=open(file_object.name,mode='wb')
    for i in file_object.chunks():
        f.write(i)
    f.close()

    return HttpResponse('....')

class upForm(BootrsapForm):
    bootrsap_exitis_forms = ['img']
    name=forms.CharField(label='姓名')
    age=forms.IntegerField(label='年龄')
    img=forms.FileField(label='头像')

def upload_form(request):
    title='Form上传'
    if request.method=='GET':
        do_object=models.Boss.objects.all()
        # print(do_object)
        form = upForm()
        return render( request, 'upload_form.html', {'form': form, 'title': title,'do':do_object} )
    form=upForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # 读取到内容
        # {'name': '张三', 'age': 12, 'img': <InMemoryUploadedFile: 辉.jpg (image/jpeg)>}
        # print(form.cleaned_data)
        #1.读取图片内容，写入到文件夹中并获取到文件路径
        file_object=form.cleaned_data.get('img')

        # file_path='/app02/static/img/{}'.format(file_object.name)
        # 存放在数据库中的路径，方便读取
        # do_file_path=os.path.join('static','img',file_object.name)

        #绝对路径
        # media_path = os.path.join(settings.MEDIA_ROOT, file_object.name )
        # 相对路径
        media_path = os.path.join('media', file_object.name )
        #存放在文件夹中的路径
        # file_path=os.path.join('app02','static','img',file_object.name)
        f=open(media_path,mode='wb')
        for chunk in file_object.chunks():
            f.write(chunk)
        f.close()

        #2.将图片路径写入到数据库中
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path
        )

        return redirect('/upload/form/')


    # 出现错误提示
    return render( request, 'upload_form.html', {'form': form, 'title': title} )


class UpModelForm(BootrsapModelForm):
      bootrsap_exitis_forms=['img']
      class Meta:
          model=models.City
          fields='__all__'

def upload_model_form(request):
    #上传文件跟数据（modelForm）
    title = 'modelForm上传'
    if request.method=='GET':
        form=UpModelForm()
        return render(request,'upload_model_form.html',{'title':title,'form':form})
    form=UpModelForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        # 对于文件：自动保存
        #字段+上传文件 写入数据库中
        form.save()
        return redirect('/upload/model/form/')
    return render( request, 'upload_form.html', {'form': form,'title':title,} )

